package com.uniview.filter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.uniview.entity.po.ExceptionLog;
import com.uniview.service.ExceptionLogService;
import com.uniview.util.IPUtils;
import com.uniview.util.mail.MailSenderFactory;
@ControllerAdvice
public class GlobalExceptionHandler implements HandlerExceptionResolver {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	@Autowired
	private ExceptionLogService exceptionLogService;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("ex", ex);

		if (handler instanceof HandlerMethod) {
			LOGGER.info(">>>>>>系统异常，记录异常信息到数据库------start------");
			// 远程访问IP
			String ip = IPUtils.getRemortIP(request);
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			String className = handlerMethod.getBeanType().getName();
			String methodName = handlerMethod.getMethod().getName();
			StringWriter sw = new StringWriter();
			ex.printStackTrace(new PrintWriter(sw, true));
 
			// 插入异常日志到数据库
			ExceptionLog log = new ExceptionLog();
			log.setIp(ip);
			log.setClassName(className);
			log.setMethodName(methodName);
			log.setExceptionType(ex.getClass().getSimpleName());
			log.setExceptionMsg(sw.toString()); // 异常详细信息
			log.setIsView((byte) 1); // 默认未读,1:为查看、2：已查看
			log.setAddtime(new Date());
 
			// TODO 此处先写死。后期完善，接收人从数据库配置中获取
			try {
				exceptionLogService.saveExceptionLog(log);
				LOGGER.info(">>>>>>系统异常，记录异常信息到数据库------end------");
				String recipient = "sdms@uniview.com";
				String subject = "【服务派工系统异常通知】";
				Object content = "管理员，您好：<br/>   服务派工系统系统出现异常，请立即登录后台系统：“系统管理”--“异常日志管理”进行查看。<br/>   "
						+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				MailSenderFactory.getSender().send(recipient, subject, content);
			} catch (AddressException e) {
				e.printStackTrace();
			} catch (MessagingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
                
		return null;

	}

}
